/**
 * jQuery Plugin
 * requires jQuery 1.4 or later
 *
 * Released under the MIT license
 * http://jquery.org/license
 *
 * User: wuqinglong
 * mail: hellowql@126.com
 * Date: 13-8-30
 * Time: 上午2:47
 * Version: 0.1
 */


var mongodb = require('./db');

function Article(article){
    this.name = article.name;
    this.password = article.password;
    this.email = article.email;
    this._id=article._id;
    this.title=article.title;
    this.body=article.body;
};

module.exports = Article;

Article.prototype.save = function(callback) {//存储用户信息
    //要存入数据库的用户文档
    var article = {
        name: this.name,
        password: this.password,
        email: this.email
    };
    //打开数据库
    mongodb.open(function(err, db){
        if(err){
            return callback(err);
        }
        //读取 Articles 集合
        db.collection('articles', function(err, collection){
            if(err){
                mongodb.close();
                return callback(err);
            }
            //将用户数据插入 Articles 集合
            collection.insert(article,{safe: true}, function(err, article){
                mongodb.close();
                callback(err, article);//成功！返回插入的用户信息
            });
        });
    });
};

Article.get = function(name, callback){//读取用户信息
    //打开数据库
    mongodb.open(function(err, db){
        if(err){
            return callback(err);
        }
        //读取 Articles 集合
        db.collection('articles', function(err, collection){
            if(err){
                mongodb.close();
                return callback(err);
            }
            //查找用户名 name 值为 name文档
            collection.findOne({
                name: name
            },function(err, doc){
                mongodb.close();
                if(doc){
                    var article = new Article(doc);
                    callback(err, article);//成功！返回查询的用户信息
                } else {
                    callback(err, null);//失败！返回null
                }
            });
        });
    });
};